<!--
  题库列表页面
-->
<template>
  <div class="question-bank-list">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1>题库管理</h1>
        <p>管理和组织考试题目库</p>
      </div>
      <div class="header-right">
        <el-button
          type="primary"
          :icon="Plus"
          @click="createQuestionBank"
          v-if="authStore.hasPermission('question:write')"
        >
          创建题库
        </el-button>
        <el-button
          :icon="Upload"
          @click="showImportDialog = true"
          v-if="authStore.hasPermission('question:write')"
        >
          批量导入
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" :inline="true">
        <el-form-item label="题库名称">
          <el-input
            v-model="filterForm.keyword"
            placeholder="搜索题库名称"
            clearable
            @keyup.enter="loadQuestionBanks"
          />
        </el-form-item>
        <el-form-item label="创建者">
          <el-select
            v-model="filterForm.creator"
            placeholder="选择创建者"
            clearable
            style="width: 150px"
          >
            <el-option label="全部" value="" />
            <el-option label="我创建的" value="self" />
            <el-option label="公开题库" value="public" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadQuestionBanks">
            搜索
          </el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 题库列表 -->
    <el-card class="bank-list-card">
      <div class="bank-grid">
        <div
          v-for="bank in questionBanks"
          :key="bank.id"
          class="bank-card"
          @click="viewBankDetail(bank)"
        >
          <div class="bank-header">
            <div class="bank-icon">
              <el-icon size="24"><Document /></el-icon>
            </div>
            <div class="bank-actions" @click.stop>
              <el-dropdown trigger="click" @command="handleBankAction">
                <el-button text :icon="MoreFilled" />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      :command="{ action: 'edit', bank }"
                      v-if="canEditBank(bank)"
                    >
                      编辑
                    </el-dropdown-item>
                    <el-dropdown-item
                      :command="{ action: 'copy', bank }"
                    >
                      复制
                    </el-dropdown-item>
                    <el-dropdown-item
                      :command="{ action: 'export', bank }"
                    >
                      导出
                    </el-dropdown-item>
                    <el-dropdown-item
                      :command="{ action: 'delete', bank }"
                      divided
                      v-if="canDeleteBank(bank)"
                    >
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>

          <div class="bank-content">
            <h3 class="bank-title">{{ bank.name }}</h3>
            <p class="bank-description">{{ bank.description }}</p>

            <div class="bank-stats">
              <div class="stat-item">
                <span class="stat-label">题目数量</span>
                <span class="stat-value">{{ bank.question_count }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">难度分布</span>
                <div class="difficulty-bars">
                  <div class="difficulty-bar easy" :style="{ width: getDifficultyWidth(bank, 'easy') }" />
                  <div class="difficulty-bar medium" :style="{ width: getDifficultyWidth(bank, 'medium') }" />
                  <div class="difficulty-bar hard" :style="{ width: getDifficultyWidth(bank, 'hard') }" />
                </div>
              </div>
            </div>

            <div class="bank-meta">
              <div class="meta-item">
                <el-icon><User /></el-icon>
                <span>{{ bank.creator_name }}</span>
              </div>
              <div class="meta-item">
                <el-icon><Calendar /></el-icon>
                <span>{{ formatDate(bank.created_at) }}</span>
              </div>
              <div class="meta-item">
                <el-tag :type="bank.is_public ? 'success' : 'info'" size="small">
                  {{ bank.is_public ? '公开' : '私有' }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="bank-card loading">
          <el-skeleton animated>
            <template #template>
              <div style="padding: 20px">
                <el-skeleton-item variant="h3" style="width: 60%" />
                <el-skeleton-item variant="text" style="width: 80%" />
                <el-skeleton-item variant="text" style="width: 60%" />
              </div>
            </template>
          </el-skeleton>
        </div>

        <!-- 空状态 -->
        <div v-if="!loading && questionBanks.length === 0" class="empty-state">
          <el-empty
            description="暂无题库"
            :image-size="100"
          >
            <el-button
              type="primary"
              @click="createQuestionBank"
              v-if="authStore.hasPermission('question:write')"
            >
              创建第一个题库
            </el-button>
          </el-empty>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="total > 0">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.page_size"
          :total="total"
          :page-sizes="[12, 24, 48, 96]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadQuestionBanks"
          @current-change="loadQuestionBanks"
        />
      </div>
    </el-card>

    <!-- 创建/编辑题库对话框 -->
    <el-dialog
      v-model="showBankDialog"
      :title="editingBank ? '编辑题库' : '创建题库'"
      width="600px"
      @close="resetBankForm"
    >
      <el-form
        ref="bankFormRef"
        :model="bankForm"
        :rules="bankRules"
        label-width="100px"
      >
        <el-form-item label="题库名称" prop="name">
          <el-input
            v-model="bankForm.name"
            placeholder="请输入题库名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="题库描述" prop="description">
          <el-input
            v-model="bankForm.description"
            type="textarea"
            placeholder="请输入题库描述"
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="题库标签" prop="tags">
          <el-select
            v-model="bankForm.tags"
            multiple
            filterable
            allow-create
            placeholder="添加标签"
            style="width: 100%"
          >
            <el-option
              v-for="tag in commonTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="可见性">
          <el-radio-group v-model="bankForm.is_public">
            <el-radio :label="false">私有</el-radio>
            <el-radio :label="true">公开</el-radio>
          </el-radio-group>
          <div class="form-tip">
            公开题库对所有用户可见，私有题库仅创建者可见
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showBankDialog = false">取消</el-button>
        <el-button
          type="primary"
          :loading="bankFormLoading"
          @click="saveQuestionBank"
        >
          {{ editingBank ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="showImportDialog"
      title="批量导入题目"
      width="500px"
    >
      <div class="import-content">
        <el-upload
          class="upload-area"
          drag
          accept=".xlsx,.xls,.csv"
          :auto-upload="false"
          :on-change="handleFileChange"
          :limit="1"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持 Excel、CSV 格式，文件大小不超过 10MB
            </div>
          </template>
        </el-upload>

        <div class="import-tips">
          <h4>导入说明：</h4>
          <ul>
            <li>Excel文件需包含：题目标题、题目类型、难度、分值、题目内容、答案等字段</li>
            <li>支持单选题、多选题、判断题、填空题、简答题</li>
            <li>导入前请确保数据格式正确</li>
          </ul>
        </div>
      </div>
      <template #footer>
        <el-button @click="showImportDialog = false">取消</el-button>
        <el-button
          type="primary"
          :disabled="!importFile"
          :loading="importLoading"
          @click="handleImport"
        >
          开始导入
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { useAuthStore } from '@/stores'
import { getQuestionBanks, createQuestionBank as apiCreateBank, updateQuestionBank, deleteQuestionBank, batchImportQuestions } from '@/api/questions'
import type { QuestionBank } from '@/types'
import {
  Plus,
  Upload,
  Document,
  MoreFilled,
  User,
  Calendar,
  UploadFilled
} from '@element-plus/icons-vue'

const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const loading = ref(false)
const questionBanks = ref<QuestionBank[]>([])
const total = ref(0)

// 筛选表单
const filterForm = reactive({
  keyword: '',
  creator: ''
})

// 分页
const pagination = reactive({
  page: 1,
  page_size: 12
})

// 题库表单
const showBankDialog = ref(false)
const editingBank = ref<QuestionBank | null>(null)
const bankFormLoading = ref(false)
const bankFormRef = ref<FormInstance>()

const bankForm = reactive({
  name: '',
  description: '',
  tags: [] as string[],
  is_public: false
})

const bankRules: FormRules = {
  name: [
    { required: true, message: '请输入题库名称', trigger: 'blur' },
    { min: 2, max: 50, message: '名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入题库描述', trigger: 'blur' },
    { max: 200, message: '描述不能超过 200 个字符', trigger: 'blur' }
  ]
}

// 导入相关
const showImportDialog = ref(false)
const importFile = ref<File | null>(null)
const importLoading = ref(false)

// 常用标签
const commonTags = ['数学', '英语', '物理', '化学', '生物', '历史', '地理', '政治', '计算机']

// 加载题库列表
const loadQuestionBanks = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      page_size: pagination.page_size,
      keyword: filterForm.keyword || undefined,
      creator: filterForm.creator || undefined
    }

    const response = await getQuestionBanks(params)
    questionBanks.value = response.data.results
    total.value = response.data.count
  } catch (error) {
    console.error('Failed to load question banks:', error)
    ElMessage.error('加载题库失败')
  } finally {
    loading.value = false
  }
}

// 重置筛选
const resetFilter = () => {
  filterForm.keyword = ''
  filterForm.creator = ''
  pagination.page = 1
  loadQuestionBanks()
}

// 查看题库详情
const viewBankDetail = (bank: QuestionBank) => {
  router.push(`/questions/banks/${bank.id}`)
}

// 创建题库
const createQuestionBank = () => {
  editingBank.value = null
  resetBankForm()
  showBankDialog.value = true
}

// 编辑题库
const editQuestionBank = (bank: QuestionBank) => {
  editingBank.value = bank
  Object.assign(bankForm, {
    name: bank.name,
    description: bank.description,
    tags: bank.tags || [],
    is_public: bank.is_public
  })
  showBankDialog.value = true
}

// 保存题库
const saveQuestionBank = async () => {
  if (!bankFormRef.value) return

  try {
    await bankFormRef.value.validate()
    bankFormLoading.value = true

    if (editingBank.value) {
      await updateQuestionBank(editingBank.value.id, bankForm)
      ElMessage.success('题库更新成功')
    } else {
      await apiCreateBank(bankForm)
      ElMessage.success('题库创建成功')
    }

    showBankDialog.value = false
    loadQuestionBanks()
  } catch (error) {
    console.error('Failed to save question bank:', error)
  } finally {
    bankFormLoading.value = false
  }
}

// 重置题库表单
const resetBankForm = () => {
  Object.assign(bankForm, {
    name: '',
    description: '',
    tags: [],
    is_public: false
  })
  bankFormRef.value?.clearValidate()
}

// 删除题库
const deleteQuestionBankConfirm = async (bank: QuestionBank) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除题库 "${bank.name}" 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteQuestionBank(bank.id)
    ElMessage.success('题库删除成功')
    loadQuestionBanks()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete question bank:', error)
      ElMessage.error('删除题库失败')
    }
  }
}

// 处理题库操作
const handleBankAction = ({ action, bank }: { action: string; bank: QuestionBank }) => {
  switch (action) {
    case 'edit':
      editQuestionBank(bank)
      break
    case 'copy':
      copyQuestionBank(bank)
      break
    case 'export':
      exportQuestionBank(bank)
      break
    case 'delete':
      deleteQuestionBankConfirm(bank)
      break
  }
}

// 复制题库
const copyQuestionBank = (bank: QuestionBank) => {
  editingBank.value = null
  Object.assign(bankForm, {
    name: `${bank.name} - 副本`,
    description: bank.description,
    tags: [...(bank.tags || [])],
    is_public: false
  })
  showBankDialog.value = true
}

// 导出题库
const exportQuestionBank = (bank: QuestionBank) => {
  // TODO: 实现导出功能
  ElMessage.info('导出功能开发中...')
}

// 处理文件导入
const handleFileChange = (file: any) => {
  importFile.value = file.raw
}

// 执行导入
const handleImport = async () => {
  if (!importFile.value) return

  importLoading.value = true
  try {
    // TODO: 实现导入逻辑
    ElMessage.success('导入功能开发中...')
    showImportDialog.value = false
  } catch (error) {
    console.error('Import failed:', error)
    ElMessage.error('导入失败')
  } finally {
    importLoading.value = false
  }
}

// 权限检查
const canEditBank = (bank: QuestionBank) => {
  return authStore.hasPermission('question:write') &&
         (bank.creator === authStore.user?.id || authStore.hasRole('admin'))
}

const canDeleteBank = (bank: QuestionBank) => {
  return authStore.hasPermission('question:delete') &&
         (bank.creator === authStore.user?.id || authStore.hasRole('admin'))
}

// 工具函数
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString()
}

const getDifficultyWidth = (bank: any, difficulty: string) => {
  const distribution = bank.difficulty_distribution || {}
  const total = Object.values(distribution).reduce((sum: number, count: any) => sum + count, 0)
  if (total === 0) return '0%'
  return `${(distribution[difficulty] || 0) / total * 100}%`
}

// 页面挂载时加载数据
onMounted(() => {
  loadQuestionBanks()
})
</script>

<style scoped lang="scss">
.question-bank-list {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-bottom: 24px;

    .header-left {
      h1 {
        font-size: 28px;
        color: var(--el-text-color-primary);
        margin: 0 0 8px 0;
      }

      p {
        font-size: 14px;
        color: var(--el-text-color-regular);
        margin: 0;
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
    }
  }

  .filter-card {
    margin-bottom: 24px;
  }

  .bank-list-card {
    .bank-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
      gap: 20px;
      margin-bottom: 24px;

      .bank-card {
        border: 1px solid var(--el-border-color-light);
        border-radius: 12px;
        padding: 20px;
        cursor: pointer;
        transition: all 0.3s;
        background: var(--el-bg-color);

        &:hover {
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          transform: translateY(-2px);
        }

        &.loading {
          cursor: default;
        }

        .bank-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          margin-bottom: 16px;

          .bank-icon {
            width: 48px;
            height: 48px;
            background: var(--el-color-primary-light-9);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--el-color-primary);
          }

          .bank-actions {
            opacity: 0;
            transition: opacity 0.3s;
          }
        }

        &:hover .bank-actions {
          opacity: 1;
        }

        .bank-content {
          .bank-title {
            font-size: 18px;
            font-weight: 600;
            color: var(--el-text-color-primary);
            margin: 0 0 8px 0;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .bank-description {
            font-size: 14px;
            color: var(--el-text-color-regular);
            margin: 0 0 16px 0;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }

          .bank-stats {
            margin-bottom: 16px;

            .stat-item {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 8px;

              .stat-label {
                font-size: 13px;
                color: var(--el-text-color-regular);
              }

              .stat-value {
                font-size: 16px;
                font-weight: 600;
                color: var(--el-text-color-primary);
              }

              .difficulty-bars {
                display: flex;
                height: 6px;
                border-radius: 3px;
                overflow: hidden;

                .difficulty-bar {
                  height: 100%;

                  &.easy {
                    background: var(--el-color-success);
                  }

                  &.medium {
                    background: var(--el-color-warning);
                  }

                  &.hard {
                    background: var(--el-color-danger);
                  }
                }
              }
            }
          }

          .bank-meta {
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 12px;
            color: var(--el-text-color-placeholder);

            .meta-item {
              display: flex;
              align-items: center;
              gap: 4px;
            }
          }
        }
      }

      .empty-state {
        grid-column: 1 / -1;
        text-align: center;
        padding: 60px 20px;
      }
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
    }
  }

  .form-tip {
    font-size: 12px;
    color: var(--el-text-color-regular);
    margin-top: 4px;
  }

  .import-content {
    .upload-area {
      margin-bottom: 20px;
    }

    .import-tips {
      h4 {
        font-size: 14px;
        margin: 0 0 12px 0;
        color: var(--el-text-color-primary);
      }

      ul {
        margin: 0;
        padding-left: 20px;

        li {
          font-size: 13px;
          color: var(--el-text-color-regular);
          margin-bottom: 4px;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .question-bank-list {
    .page-header {
      flex-direction: column;
      align-items: stretch;
      gap: 16px;

      .header-right {
        justify-content: flex-start;
      }
    }

    .bank-list-card {
      .bank-grid {
        grid-template-columns: 1fr;
        gap: 16px;
      }
    }
  }
}
</style>